package com.quyunshuo.module.home.fragment.me

import android.os.Build
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.compose.runtime.snapshots.Snapshot.Companion.observe
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.kizitonwose.calendar.core.CalendarDay
import com.kizitonwose.calendar.view.MonthDayBinder
import com.kizitonwose.calendar.view.ViewContainer
import com.quyunshuo.edwinpro.common.ui.BaseFragment
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.activity.help.HelpActivity
import com.quyunshuo.module.home.activity.history.HistoryActivity
import com.quyunshuo.module.home.activity.stat.StatActivity
import com.quyunshuo.module.home.databinding.HomeFragmentMeBinding
import com.quyunshuo.module.home.fragment.me.compose.LevelPage
import com.quyunshuo.module.home.room.entity.ConcentrationEntity
import com.quyunshuo.module.home.util.SettingsDataStore
import com.tencent.bugly.Bugly.applicationContext
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.YearMonth
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale

/**
 * @author DBoy 2021/7/6 <p>
 * - 文件描述 : 测试fragment
 */
@AndroidEntryPoint
class MeFragment : BaseFragment<HomeFragmentMeBinding, MeViewModel>() {
    private val TAG = "HomeFragment"
    override val mViewModel by viewModels<MeViewModel>()
    override fun createVB() = HomeFragmentMeBinding.inflate(layoutInflater)
    override fun HomeFragmentMeBinding.initListener() {


    }

    // 1. 定义日期单元格的视图容器类
    // 这个类负责持有日期单元格中的视图元素
    class DayViewContainer(view: View) : ViewContainer(view) {
        // 获取布局文件中的TextView用于显示日期数字
        val textView: TextView = view.findViewById(R.id.calendarDayText)
    }

    // 2. 创建日期绑定器
    // 这个绑定器负责将数据绑定到每个日期单元格视图
    private val dayBinder = object : MonthDayBinder<DayViewContainer> {
        private lateinit var concentrationEntities: List<ConcentrationEntity>
        fun setData(concentrationEntities: List<ConcentrationEntity>) {
            this.concentrationEntities = concentrationEntities
        }

        // 创建视图容器实例
        // 当需要新的日期单元格时调用此方法
        override fun create(view: View) = DayViewContainer(view)

        // 绑定数据到日期单元格
        // 当日期单元格需要显示数据时调用此方法
        @RequiresApi(Build.VERSION_CODES.O)
        override fun bind(container: DayViewContainer, data: CalendarDay) {
            val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
            val dateString = data.date.format(dateFormatter)
            // 4. 查找匹配的专注记录
            val matchingRecord = concentrationEntities.find { it.focusDate == dateString }
            container.textView.isSelected = matchingRecord != null
            // 设置日期数字文本
            container.textView.text = data.date.dayOfMonth.toString()
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun HomeFragmentMeBinding.initView() {
        val dataStore = SettingsDataStore(requireContext())

        // 观察震动设置变化
        lifecycleScope.launch {
            dataStore.vibrationSetting.collect {
                //监听数据的变化
                Log.d(TAG, "vibrationSetting: ${it}")
            }

        }
        lifecycleScope.launch {
            dataStore.saveVibrationSetting(false)
        }
        dataNext.setOnClickListener {
            //todo 进入数据统计页面
            StatActivity.newInstance(requireContext())
        }
        help.setOnClickListener {
            HelpActivity.newInstance(requireContext())
        }
        homeHis.setOnClickListener {
            HistoryActivity.newInstance(requireContext())
        }
        // 从布局文件中获取CalendarView组件
        // 3. 将日期绑定器设置到CalendarView
        calendarView.dayBinder = dayBinder
        mViewModel.getAll2()

    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun initObserve() {
        lifecycleScope.launch {
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initRequestData() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                mViewModel.getData().collect {
                    mBinding.day.text = it.toString()
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                mViewModel.getData().collect {
                    mBinding.day.text = it.toString()
                }
            }
        }
        // 方案一
//        lifecycleScope.launch {
//            mViewModel.getAll().collect{
//                dayBinder.setData(it)
//
//                // 获取当前年月（例如2025-07）
//                val currentMonth = YearMonth.now()
//
//                // 设置日历范围：
//                // 开始月份 = 当前月份往前推12个月
//                // 结束月份 = 当前月份往后推12个月
//                // 一周的第一天设置为星期一（符合中国习惯）
//                mBinding.calendarView.setup(
//            startMonth = currentMonth.minusMonths(12),
//            endMonth = currentMonth.plusMonths(12),
//            firstDayOfWeek = DayOfWeek.MONDAY
//        )
//                // 1. 设置日历只显示当前月份
////                mBinding.calendarView.setup(
////                    startMonth = currentMonth, // 开始月份设置为当前月
////                    endMonth = currentMonth,   // 结束月份也设置为当前月
////                    firstDayOfWeek = DayOfWeek.MONDAY // 以周一作为每周的第一天
////                )
//
//                // 滚动到当前月份
//                mBinding.calendarView.scrollToMonth(currentMonth)
//            }
//
//        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                mViewModel.dataAll.collect {
                    it?.let {
                        when (it) {
                            is Resource.Error -> {

                            }

                            Resource.Loading -> {
                                mBinding.loading.isVisible = true
                            }

                            is Resource.Success<List<ConcentrationEntity>> -> {
                                mBinding.level.setContent {
                                    LevelPage(it.data.size)
                                }

                                mBinding.loading.isVisible = false

                                dayBinder.setData(it.data)
                                // 获取当前年月（例如2025-07）
                                val currentMonth = YearMonth.now()
                                // 设置日历范围：
                                // 开始月份 = 当前月份往前推12个月
                                // 结束月份 = 当前月份往后推12个月
                                // 一周的第一天设置为星期一（符合中国习惯）
                                mBinding.calendarView.setup(
                                    startMonth = currentMonth.minusMonths(12),
                                    endMonth = currentMonth.plusMonths(12),
                                    firstDayOfWeek = DayOfWeek.MONDAY
                                )
                                // 1. 设置日历只显示当前月份
//                        mBinding.calendarView.setup(
//                            startMonth = currentMonth, // 开始月份设置为当前月
//                            endMonth = currentMonth,   // 结束月份也设置为当前月
//                            firstDayOfWeek = DayOfWeek.MONDAY // 以周一作为每周的第一天
//                        )
                                // 滚动到当前月份
                                mBinding.calendarView.scrollToMonth(currentMonth)
                            }
                        }

                    }
                }
            }
        }
    }


}